package com.zhangtai.modules.service.impl.qw;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.zhangtai.modules.dao.QwCheckinMonthDao;
import com.zhangtai.modules.dto.ExportQwCheckMonthTableDto;
import com.zhangtai.modules.entity.qw.QwCheckinMonthEntity;
import com.zhangtai.modules.service.qw.QwCheckinMonthService;
import com.zhangtai.modules.service.qw.QwCheckinsService;
import com.zhangtai.utils.PageUtils;
import com.zhangtai.utils.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


@Service("qwCheckinMonthService")
public class QwCheckinMonthServiceImpl extends ServiceImpl<QwCheckinMonthDao, QwCheckinMonthEntity> implements QwCheckinMonthService {
    @Autowired
    private QwCheckinsService qwCheckinsService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<QwCheckinMonthEntity> page = this.page(
                new Query<QwCheckinMonthEntity>().getPage(params),
                new QueryWrapper<QwCheckinMonthEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public void saveCheckMonth(int startTimes, int endTimes, String[] userids) {
        List<QwCheckinMonthEntity> collect = null;
        try {
            List<Map<String, Object>> checkAllTables = qwCheckinsService.getCheckAllTables(startTimes, endTimes, userids);
            collect = checkAllTables.stream().map(item -> {
                ExportQwCheckMonthTableDto exportQwCheckMonthTableDto = JSON.parseObject(JSON.toJSONString(item), ExportQwCheckMonthTableDto.class);
                QwCheckinMonthEntity qwCheckinMonthEntity = new QwCheckinMonthEntity();
                BeanUtils.copyProperties(exportQwCheckMonthTableDto, qwCheckinMonthEntity);
                qwCheckinMonthEntity.setDate(new SimpleDateFormat("yyyy-MM").format(new Date(startTimes * 1000L)));
                JSONObject jsonObject = JSONUtil.parseObj(item);
                qwCheckinMonthEntity.setMonthCheckTotal(jsonObject.toString());
                return qwCheckinMonthEntity;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.saveBatch(collect);
    }

}